package com.wyp168.leetcode.faceQ;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @ClassName AnyThreadPrintSolution
 * @Title TODO
 * @Description TODO
 * @Author wyp168
 * @Date 2022/12/4 11:45
 */
public class AnyThreadPrintSolution {
    public static void main(String[] args){
        Set<String> set = new HashSet<>();


        System.out.println(set.contains("123"));
//        AnyThreadPrintSolution anyThreadPrintSolution = new AnyThreadPrintSolution();
//        anyThreadPrintSolution.runAnyThready(8, 3);
    }

    volatile int[] arr;

    public void runAnyThready(int m, int n){
        AtomicInteger count = new AtomicInteger(0);
        arr = new int[m];
        if (m > 1) {
            arr[0] = 2347;
            arr[1] = 3917;
        }

        // 填充信号量
        Semaphore[] semaphores = new Semaphore[n];
        for (int i = 0; i < semaphores.length; i++) {
            semaphores[i] = new Semaphore(0);
        }
        //初始第一个线程信号量为1
        semaphores[0].release();

        //定义n个线程，并使之与信号量数组semaphores 进行一一关联
        Thread[] threads = new Thread[n];

        for(int i = 0; i < n; i ++) {
            int finalIndex = i;
            threads[i] = new Thread(() -> {
                while (true) {
                    try {
                        semaphores[finalIndex].acquire();
                        int intIndex;
                        if ((intIndex = count.getAndIncrement()) > 1 && intIndex < m) {
                            arr[intIndex] = arr[intIndex - 1] + arr[intIndex - 2];
                        }
                        if (intIndex < m) {
                            System.out.println(arr[intIndex] + "---->" + Thread.currentThread().getName());
                        }

                        semaphores[(finalIndex + 1) % n].release();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }, "t" + i);
            threads[i].start();
        }

    }
}
